﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.EntityFrameworkCore;

namespace Jack.EntityFrameworkCore
{
    public static class PagedListExtensions
    {
        public static async Task<IPagedList<TModel>> ToPagedListAsync<TModel>(this IQueryable<TModel> query, int currentPage, int pageSize, CancellationToken cancellationToken = default)
        {
            if (currentPage < 1)
            {
                currentPage = 1;
            }

            int realPageIndex = currentPage - 1;
            return new PagedList<TModel>(totalCount: await query.CountAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false), items: await query.Skip(realPageIndex * pageSize).Take(pageSize).ToListAsync(cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false), currentPage: currentPage, pageSize: pageSize);
        }
    }
}
